<template>
  <div class="Login">
    <div class="form">
      <h2>系统登陆</h2>
      <el-form :model="LoginForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
        <el-form-item prop="name">
          <el-input type="text" v-model="LoginForm.name" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="pass">
          <el-input type="password" v-model="LoginForm.pass" show-password placeholder="请输入密码"></el-input>
        </el-form-item>
        <div class="code">
          <div class="input">
            <el-form-item prop="captcha">
              <el-input
                @keyup.enter.native.prevent="submitForm(LoginForm)"
                type="text"
                v-model="LoginForm.captcha"
                placeholder="请输入验证码"
              ></el-input>
            </el-form-item>
          </div>
          <div class="verificationCode">
            <img id="imgCode" :src="captchaSvg" alt="验证码获取失败，请稍后再试" />
            <span @click="refresh">刷新验证码</span>
          </div>
        </div>
        <el-form-item>
          <el-button :loading="loading" type="primary" @click.prevent="submitForm(LoginForm)">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
    <footer>© 2022-2023 桂ICP备2 022008283号-1</footer>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      LoginForm: {
        name: "admin",
        pass: "admin",
        captcha: ""
      },
      rules: {
        name: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
        pass: [{ required: true, message: "密码不能为空", trigger: "blur" }],
        captcha: [
          { required: true, message: "验证码不能为空", trigger: "blur" },
          { min: 4, max:4, message: "验证码长度错误", trigger: "blur"}
        ]
      },
      captchaSvg: "",
      codeMap: {}
    };
  },
  methods: {
    base64(svg) {
      return (
        "data:image/svg+xml;base64," +
        window.btoa(unescape(encodeURIComponent(svg)))
      );
    },
    refresh() {
      let fn = () => {
        this.$api
          .get("/captcha")
          .then(res => {
            this.captchaSvg = this.base64(res.data);
            this.codeMap["base64"] = this.base64(res.data);
          })
          .catch(error => {
            if (error.response && error.response.status === 400) {
              this.captchaSvg = this.codeMap["base64"];
            }
          });
      };

      this.$Public.debounce(() => fn(), 500)();
    },

    submitForm(form) {
      this.$refs.ruleForm
        .validate()
        .then(res => {
          this.loading = true;
          let Form = structuredClone(form);
          Form.captcha = form.captcha.toLowerCase();
          this.$api
            .post("/login", form, {
              headers: {
                "Content-Type": "application/json"
              }
            })
            .then(res => {
              this.loading = false;
              this.$store.commit("setToken", res.data.Token);
              this.$router.push("/");
            })
            .catch(error => {
              this.loading = false;
              return;
            });
        })
        .catch(err => {
          this.$message.error("请检查表单");
        });
    }
  },

  created() {
    this.$api
      .get("/captcha")
      .then(res => {
        this.captchaSvg = this.base64(res.data);
        this.codeMap["base64"] = this.base64(res.data);
        localStorage.setItem("base64", this.codeMap["base64"]);
      })
      .catch(error => {
        if (error.response && error.response.status === 400) {
          this.codeMap["base64"] = localStorage.getItem("base64");
          this.captchaSvg = this.codeMap["base64"];
        }
      });
  }
};
</script>

<style scoped>
.Login {
  background-color: #2d3a4b;
  color: #fff;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.form {
  width: 350px;
  height: 300px;
}

.form h2 {
  text-align: center;
  margin-bottom: 30px;
}

footer {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  text-align: center;
  height: 35px;
  background-color: #26313f;
  line-height: 35px;
  font-size: 12px;
}

.verificationCode {
  position: relative;
  height: 45px;
  width: 80px;
}

#imgCode {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #fff;
  height: 40px;
  width: 80px;
}

span {
  display: none;
}

.verificationCode:hover span {
  cursor: pointer;
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  font-size: 11px;
  line-height: 45px;
  color: rgba(0, 60, 255, 0.615);
  width: 100%;
  height: 40px;
  background-color: rgba(0, 140, 255, 0.658);
  user-select: none;
}

.demo-ruleForm >>> .is-required div div .el-input__inner {
  background-color: #26313f;
  color: #fff;
  border: 1px solid #666;
  height: 45px;
}

.el-form-item__label {
  color: #fff;
}

.el-button {
  width: 100%;
}

.code {
  display: flex;
}

.code .input {
  width: 270px;
}
</style>
